// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from 'vue'
import FastClick from 'fastclick'
import VueRouter from 'vue-router'
import router from './router/index.js'
import App from './App'
import Vuex from 'vuex'
import './css/iconfont.css'
import Axios from './util/axios'

Vue.use(VueRouter)
Vue.use(Vuex)

FastClick.attach(document.body)

Vue.config.productionTip = false
Vue.prototype.$http = Axios // 类似于vue-resource的调用方法，之后可以在实例里直接用this.$http.get()等

//原生端交互
/*这段代码是固定的，必须要放到js中*/
function setupWebViewJavascriptBridge(callback) {
	if (window.WebViewJavascriptBridge) {
		return callback(WebViewJavascriptBridge);
	}
	if (window.WVJBCallbacks) {
		return window.WVJBCallbacks.push(callback);
	}
	window.WVJBCallbacks = [callback];
	var WVJBIframe = document.createElement('iframe');
	WVJBIframe.style.display = 'none';
	WVJBIframe.src = 'wvjbscheme://__BRIDGE_LOADED__';
	document.documentElement.appendChild(WVJBIframe);
	setTimeout(function() {
		document.documentElement.removeChild(WVJBIframe)
	}, 0)
}

/*与OC交互的所有JS方法都要放在此处注册，才能调用通过JS调用OC或者让OC调用这里的JS*/
setupWebViewJavascriptBridge(function(bridge) {
	var uniqueId = 1

	function log(message, data) {
		var log = document.getElementById('log')
		var el = document.createElement('div')
		el.className = 'logLine'
		el.innerHTML = uniqueId++ + '. ' + message + ':<br/>' + JSON.stringify(data)
		if (log.children.length) {
			log.insertBefore(el, log.children[0])
		} else {
			log.appendChild(el)
		}
	}
	/* Initialize your app here */

	/*我们在这注册一个js调用OC的方法，不带参数，且不用ObjC端反馈结果给JS：打开本demo对应的博文*/
	bridge.registerHandler('openWebviewBridgeArticle', function() {
			log("openWebviewBridgeArticle was called with by ObjC")
		})
		/*JS给ObjC提供公开的API，在ObjC端可以手动调用JS的这个API。接收ObjC传过来的参数，且可以回调ObjC*/
	bridge.registerHandler('getUserInfos', function(data, responseCallback) {
		log("Get user information from ObjC: ", data)
		responseCallback({
			'userId': '123456',
			'blog': '标哥的技术博客'
		})
	})

	/*JS给ObjC提供公开的API，ObjC端通过注册，就可以在JS端调用此API时，得到回调。ObjC端可以在处理完成后，反馈给JS，这样写就是在载入页面完成时就先调用*/
	bridge.callHandler('getUserIdFromObjC', function(responseData) {
		log("JS call ObjC's getUserIdFromObjC function, and js received response:", responseData)
	})

	document.getElementById('inviteClick').onclick = function(e) {
		log('js call objc: getBlogNameFromObjC')
		bridge.callHandler('getBlogNameFromObjC', {
			'blogURL': 'http://www.henishuo.com'
		}, function(response) {
			log('JS got response', response)
		})
	}
})


//全局title
Vue.directive('title', {
	inserted: function(el, binding) {
		document.title = el.innerText
		el.remove()
	}
})

/**
 * you can add your module here
 */
let store = new Vuex.Store({
	modules: {
		// i18n: vuexI18n.store
	}
})

store.registerModule('vux', {
	state: {
		demoScrollTop: 0,
		isLoading: false,
		direction: 'forward'
	},
	mutations: {
		updateDemoPosition(state, payload) {
			state.demoScrollTop = payload.top
		},
		updateLoadingStatus(state, payload) {
			state.isLoading = payload.isLoading
		},
		updateDirection(state, payload) {
			state.direction = payload.direction
		}
	},
	actions: {
		updateDemoPosition({
			commit
		}, top) {
			commit({
				type: 'updateDemoPosition',
				top: top
			})
		}
	}
})

// simple history management
const history = window.sessionStorage
history.clear()
let historyCount = history.getItem('count') * 1 || 0
history.setItem('/', 0)

router.beforeEach(function(to, from, next) {
	store.commit('updateLoadingStatus', {
		isLoading: true
	})

	const toIndex = history.getItem(to.path)
	const fromIndex = history.getItem(from.path)

	if (toIndex) {
		if (!fromIndex || parseInt(toIndex, 10) > parseInt(fromIndex, 10) || (toIndex === '0' && fromIndex === '0')) {
			store.commit('updateDirection', {
				direction: 'forward'
			})
		} else {
			store.commit('updateDirection', {
				direction: 'reverse'
			})
		}
	} else {
		++historyCount
		history.setItem('count', historyCount)
		to.path !== '/' && history.setItem(to.path, historyCount)
		store.commit('updateDirection', {
			direction: 'forward'
		})
	}

	if (/\/http/.test(to.path)) {
		let url = to.path.split('http')[1]
		window.location.href = `http${url}`
	} else {
		next()
	}
})

router.afterEach(function(to) {
	store.commit('updateLoadingStatus', {
		isLoading: false
	})
	if (process.env.NODE_ENV === 'production') {
		// ga && ga('set', 'page', to.fullPath)
		// ga && ga('send', 'pageview')
	}
})

/* eslint-disable no-new */
new Vue({
	store,
	router,
	render: h => h(App)
}).$mount('#app-box')